﻿/*
 * Description: 处理WMS->MES返件领用json
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * create Date:2025.9.22
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Collections;
using DatabaseAccess.DBUtility;
using Newtonsoft.Json;
using System.Data;
using log4net;
using System.IO;

namespace SendIndustrialNetwork.Service
{
    class SaveDealFaultBillService
    {
        /// <summary>
        /// 数据处理（唯一对外方法）
        /// </summary>
        public void Excute()
        {
            SaveDealFaultBill();
        }

        void SaveDealFaultBill()
        {
            try
            {
                string folderPath = ConfigurationManager.AppSettings["saveFilePath"].ToString();
                if (!Directory.Exists(folderPath)) return;
                // 获取指定路径下的所有文件（不包含子目录）
                string[] files = Directory.GetFiles(folderPath);
                // 遍历所有文件并输出文件名
                foreach (string file in files)
                {
                    // 获取仅包含文件名（不含路径）
                    string fileName = Path.GetFileName(file);
                    if (!fileName.StartsWith("WMS-MES_RETURN_USE-")) continue;
                    string filepath = folderPath + "\\" + fileName;
                    string jsonContent = File.ReadAllText(filepath).Trim();
                    if (jsonContent.ToString() == "")
                    {
                        File.Delete(filepath);
                        continue;
                    };

                    Dictionary<string, object> dict = new Dictionary<string, object>();
                    try
                    {
                        dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonContent);
                    }
                    catch (Exception)
                    {
                        LogHelp.WriteLog(string.Format("文件不是合法json", jsonContent));
                        File.Delete(filepath);
                        continue;
                    }

                    if (!dict.ContainsKey("returnNo"))
                    {
                        LogHelp.WriteLog(string.Format("json缺少【returnNo】字段", jsonContent));
                        File.Delete(filepath);
                        continue;
                    }

                    DataTable dtDealFaultBill = GetDealFaultBill(dict["returnNo"].ToString());
                    if (dtDealFaultBill.Rows.Count == 0)
                    {
                        LogHelp.WriteLog(string.Format("返件单号:【{0}】在MES中不存在", dict["returnNo"].ToString()));
                        File.Delete(filepath);
                        continue;
                    }
                    else
                    {
                        string transferstatus = dtDealFaultBill.Rows[0]["transferstatus"].ToString();
                        if (transferstatus == "7" || transferstatus == "6")
                        {
                            LogHelp.WriteLog(string.Format("返件单号:【{0}】已返件返回，不能重复返件返回", dict["returnNo"].ToString()));
                            File.Delete(filepath);
                            continue;
                        }
                    }

                    string sql = @"UPDATE dealfaultbill dt SET dt.transferstatus='6' WHERE dt.dealfaultbillname = '{0}'";
                    sql = string.Format(sql, dict["returnNo"].ToString());

                    int count = DatabaseHelper.ExecuteSql(sql);
                    if (count > 0)
                    {
                        LogHelp.WriteLog(string.Format("返件单号:【{0}】返件返回成功", dict["returnNo"].ToString()));
                    }
                    File.Delete(filepath);//删除掉json文件
                }

            }
            catch (Exception ex)
            {
                LogHelp.WriteLog(ex.Message);
            }
        }

        DataTable GetDealFaultBill(string dealfaultbillname)
        {
            string sql = @"SELECT db.* FROM dealfaultbill db WHERE db.dealfaultbillname = '{0}'";
            sql = string.Format(sql, dealfaultbillname);
            return DatabaseHelper.Query_ReturnDatTable(sql);
        }
    }
}
